<?php

class ProductController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        // action body
    }

    public function prodformAction()
    {
        $request = $this->getRequest();
        
        $sessProduct = new Zend_Session_Namespace('Product');
        
        $country_mapper = new Application_Model_CountryMapper();
        $category_mapper = new Application_Model_CategoryMapper();
        
        $this->view->categoryEntries = $category_mapper->findAll();
        
        if($sessProduct != NULL){
        	$this->view->productVal = $sessProduct->product;
	 		$this->view->descriptionVal = $sessProduct->description;
	 		$this->view->priceVal = $sessProduct->price;
	 		$this->view->quantityVal = $sessProduct->quantity;
	 		$this->view->newVal = $sessProduct->new;
	 		$this->view->countryVal = $sessProduct->country;
	 		$this->view->dayVal = $sessProduct->day;
	 		$this->view->tradeVal = $sessProduct->trade;
	 		$this->view->depositVal = $sessProduct->deposit;
	 		$this->view->deliveryVal = $sessProduct->delivery;
	 		$this->view->paypalVal = $sessProduct->paypal;
	 		$this->view->bankVal = $sessProduct->bank;
	 		$this->view->chequeVal = $sessProduct->cheque;
	 		$this->view->othersVal = $sessProduct->others;
        }
        
        $this->view->countryEntries = $country_mapper->findAll();
                        
                        $this->view->assign('action', $request->getBaseURL()."/product/addprod");
                        $this->view->assign('title' , '幫我買...');
                        $this->view->assign('product' , '物品名稱');
                        $this->view->assign('quantity' , '數量');
                        $this->view->assign('status' , '新淨度');
                        $this->view->assign('tag' , '標籤 (以;分開)');
                        $this->view->assign('country' , '物品所在國家');
                        $this->view->assign('description' , '產品描述');
                        $this->view->assign('price' , '最高價格');
                        $this->view->assign('image' , '主圖片');
                        $this->view->assign('subImage' , '副圖片');
                        $this->view->assign('validTime' , '有效時間');
                        $this->view->assign('tradeMethod' , '交易方式');
                        $this->view->assign('payFirst','先付款後發貨');
                        $this->view->assign('payLater','收貨後付款');
                        $this->view->assign('payDeposit','先付訂金, 收貨再付尾數');
                        $this->view->assign('validDate','刊登日數');
                        $this->view->assign('day','日');
                        $this->view->assign('payment','收款方式 ');
                        $this->view->assign('paypal','Paypal');
                        $this->view->assign('bankTransfer','銀行轉帳 ');
                        $this->view->assign('cheque','匯票╱銀行支票 ');
                        $this->view->assign('others','其他(見描述) ');
                        $this->view->assign('delivery' , '交收方式');
                        $this->view->assign('face' , '見面交收');
                        $this->view->assign('mail' , '郵寄');
                        $this->view->assign('changeImage' , '[ 轉換驗證碼 ]');
                        $this->view->assign('back' , '上一步');
                        $this->view->assign('next' , '下一步');
                        $this->view->assign('submit' , '提交');
    }

    public function addprodAction()
    {
 		$request = $this->getRequest();
    	
 		$sessLogin = new Zend_Session_Namespace('Login');
 		$sessProduct = new Zend_Session_Namespace('Product');
 		
 		$_product = $this->getRequest()->getPost('product');
 		$_description = $this->getRequest()->getPost('description');
 		$_price = $this->getRequest()->getPost('price');
 		$_quantity = $this->getRequest()->getPost('quantity');
 		$_new = $this->getRequest()->getPost('status');
 		$_country = $this->getRequest()->getPost('country');
 		$_category = $this->getRequest()->getPost('category');
 		$_day = $this->getRequest()->getPost('day');
 		$_trade = $this->getRequest()->getPost('payGroup');
 		$_deposit = $this->getRequest()->getPost('deposit');
 		$_delivery = $this->getRequest()->getPost('deliveryGroup');
 		$_paypal = $this->getRequest()->getPost('paypal');
 		$_bank = $this->getRequest()->getPost('bank');
 		$_cheque = $this->getRequest()->getPost('cheque');
 		$_others = $this->getRequest()->getPost('others');
 		
 		$sessProduct->product = $_product;
 		$sessProduct->description = $_description;
 		$sessProduct->price = $_price;
 		$sessProduct->quantity = $_quantity;
 		$sessProduct->new = $_new;
 		$sessProduct->country = $_country;
 		$sessProduct->category = $_category;
 		$sessProduct->day = $_day;
 		$sessProduct->trade = $_trade;
 		$sessProduct->deposit = $_deposit;
 		$sessProduct->delivery = $_delivery;
 		$sessProduct->paypal = $_paypal;
 		$sessProduct->bank = $_bank;
 		$sessProduct->cheque = $_cheque;
 		$sessProduct->others = $_others;
 		
 		
    	// The following include is required in order to call 
		// the isChallengeAccepted() function.
		
		
 		
    	/*$captcha = $request->getPost('captcha');
		$captchaId = $captcha['id']; 
		// And here's the user submitted word... 
		$captchaInput = strtolower($captcha['input']); 
		// We are accessing the session with the corresponding namespace 
		// Try overwriting this, hah! 
		$captchaSession = new Zend_Session_Namespace('Zend_Form_Captcha_'.$captchaId); 
		// To access what's inside the session, we need the Iterator
		// So we get one... 
		$captchaIterator = $captchaSession->getIterator(); 
		// And here's the correct word which is on the image... 
		$captchaWord = $captchaIterator['word'] ; 

    	if ($captchaInput != $captchaWord) {
		  // the code was incorrect
		  // you should handle the error so that the form processor doesn't continue
		
		  // or you can use the following code if there is no validation or you do not know how
		  echo "The security code entered was incorrect.<br /><br />";
		  echo "Please go <a href='javascript:history.go(-1)'>back</a> and try again.";
		  exit;
		}*/
		
    	$CHALLENGE_FIELD_PARAM_NAME = "verificationCode"; 
		
		require_once('/function/DRBImageVerification/includes/challenge.php');
	
		// If there was a form post, handle it 
		if($request->getPost($CHALLENGE_FIELD_PARAM_NAME) != NULL) {
			// Check challenge string
			if(isChallengeAccepted($request->getPost($CHALLENGE_FIELD_PARAM_NAME)) === FALSE) {
			    $this->view->assign('result', '驗證碼錯誤!現在將返回出POST頁面。');
                $this->view->assign('action', $request->getBaseURL()."/product/prodform");
			}
			else{
				$mbm_mapper = new Application_Model_MemberMapper();
	        	$product_buy_model = new Application_Model_ProductBuy();
	        	$pb_mapper = new Application_Model_ProductBuyMapper();
	        	
	        	Zend_Date::setOptions(array('format_type' => 'php'));
	        	$date = new Zend_Date();
	                
                        if($_paypal != "Y"){
                        	$_paypal = "N";
                        }
                        if($_bank != "Y"){
                        	$_bank = "N";
                        }
                        if($_cheque != "Y"){
                        	$_cheque = "N";
                        }        
                        if($_others != "Y"){
                        	$_others = "N";
                        }
                        
                        $product_buy_model->setMember_id($sessLogin->mbmId);
                        $product_buy_model->setTitle($_product);
                        $product_buy_model->setDescription($_description);
                        $product_buy_model->setPrice($_price);
                        $product_buy_model->setQuantity($_quantity);
                        $product_buy_model->setImage('/storage/buyProdPhotos/default.jpg');
                        $product_buy_model->setSub_image1('/storage/buyProdPhotos/default.jpg');
                        $product_buy_model->setSub_image2('/storage/buyProdPhotos/default.jpg');
                        $product_buy_model->setCountry($_country);
                        $product_buy_model->setCategory($_category);
                        $product_buy_model->setNew($_new);
                        $product_buy_model->setDay($_day);
                        $product_buy_model->setTrade($_trade);
                        $product_buy_model->setDeposit($_deposit);
                        $product_buy_model->setDelivery($_delivery);
                        $product_buy_model->setPaypal($_paypal);
                        $product_buy_model->setBank($_bank);
                        $product_buy_model->setCheque($_cheque);
                        $product_buy_model->setOthers($_others);
                        $product_buy_model->setStatus("B");
                        $product_buy_model->setCreation_time($date->toString('Y-m-d H:i:s'));
                        
                        $pb_mapper->insertAll($product_buy_model);
                        
                        $prodBuyEntry = $pb_mapper->findByMemberIdCreationTime($sessLogin->mbmId, $date->toString('Y-m-d H:i:s'));
                        $product_buy_id = $prodBuyEntry[0]->product_buy_id;
                        
						if(isset($_POST['tags'])) {
							$email_from = "info@thingslook.com";
				    		$email_subject = "You are tagged";
				    		$email_message = "Yeah";
				    		
				    		ini_set("SMTP", 'smtp.thingslook.com');
							ini_set("smtp_port", 25);
				    		
							foreach ($_POST['tags'] as $key => $value)
							{
							    $mbmEntry = $mbm_mapper->findByMemberId($value);
							   	$email_to = trim($mbmEntry[0]->email);
							   	
							   	$headers = "MIME-Version: 1.0" . "\r\n";
								$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
							   	
								$headers .= 'From: ' . $email_from . "\r\n".
								'Reply-To: ' . $email_from . "\r\n" .
								'X-Mailer: PHP/' . phpversion();
								mail($email_to, $email_subject, $email_message, $headers);
							}
						}
                        
                        //Upload Buy Product Photo
                        if(is_uploaded_file($_FILES['imgFile']['tmp_name'])) {
	                        $ext = explode(".", $_FILES['imgFile']['name']);
	                        $extension = end($ext);
	                        $extension = strtolower($extension);
	                        
	                        $filename = stripslashes($_FILES['imgFile']['name']);
	                        $uploadedfile = $_FILES['imgFile']['tmp_name'];
	                        
	                        $src = imagecreatefromjpeg($uploadedfile);
	                        
	                        list($width,$height)=getimagesize($uploadedfile);
	                        
	                        //resize the image
	                        $newwidth=200;
	                        $newheight=($height/$width)*$newwidth;
	                        $tmp=imagecreatetruecolor($newwidth,$newheight);
	                        
	                        imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
	                        
	                        $filename = 'storage/buyProdPhotos/' . $product_buy_id . '.' . $extension;
	                        
	                        imagejpeg($tmp,$filename,100);
	                        
	                        imagedestroy($src);
	                        imagedestroy($tmp);
	                        
	                        $product_buy_model->setImage('/storage/buyProdPhotos/' . $product_buy_id . '.' . $extension);
                        }
                        
                        //Upload Buy Product Sub Photo1
                        if(is_uploaded_file($_FILES['subImgFile1']['tmp_name'])) {
	                        $ext = explode(".", $_FILES['subImgFile1']['name']);
	                        $extension = end($ext);
	                        $extension = strtolower($extension);
	                        
	                        $filename = stripslashes($_FILES['subImgFile1']['name']);
	                        $uploadedfile = $_FILES['subImgFile1']['tmp_name'];
	                        
	                        $src = imagecreatefromjpeg($uploadedfile);
	                        
	                        list($width,$height)=getimagesize($uploadedfile);
	                        
	                        //resize the image
	                        $newwidth=200;
	                        $newheight=($height/$width)*$newwidth;
	                        $tmp=imagecreatetruecolor($newwidth,$newheight);
	                        
	                        imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
	                        
	                        $filename = 'storage/buyProdPhotos/sub1' . $product_buy_id . '.' . $extension;
	                        
	                        imagejpeg($tmp,$filename,100);
	                        
	                        imagedestroy($src);
	                        imagedestroy($tmp);

	                        $product_buy_model->setSub_image1('/storage/buyProdPhotos/sub1' . $product_buy_id . '.' . $extension);
                        }
                        
                        //Upload Buy Product Sub Photo2
                        if(is_uploaded_file($_FILES['subImgFile2']['tmp_name'])) {
	                        $ext = explode(".", $_FILES['subImgFile2']['name']);
	                        $extension = end($ext);
	                        $extension = strtolower($extension);
	                        
	                        $filename = stripslashes($_FILES['subImgFile2']['name']);
	                        $uploadedfile = $_FILES['subImgFile2']['tmp_name'];
	                        
	                        $src = imagecreatefromjpeg($uploadedfile);
	                        
	                        list($width,$height)=getimagesize($uploadedfile);
	                        
	                        //resize the image
	                        $newwidth=200;
	                        $newheight=($height/$width)*$newwidth;
	                        $tmp=imagecreatetruecolor($newwidth,$newheight);
	                        
	                        imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
	                        
	                        $filename = 'storage/buyProdPhotos/sub2' . $product_buy_id . '.' . $extension;
	                        
	                        imagejpeg($tmp,$filename,100);
	                        
	                        imagedestroy($src);
	                        imagedestroy($tmp);
	                        
	                        $product_buy_model->setSub_image2('/storage/buyProdPhotos/sub2' . $product_buy_id . '.' . $extension);
                        }
                        
                        $product_buy_model->setProduct_buy_id($product_buy_id);
                        $pb_mapper->updateAll($product_buy_model);
                        
                        Zend_Session::namespaceUnset('Product');
                        
                        /*** update credit ***/
                        $default_post_credit = 5;
                        
                        $mbmEntry = $mbm_mapper->findByMemberId($sessLogin->mbmId);
                        $exsit_deal_credit = $mbmEntry[0]->deal_credit;
                        $mbmEntry[0]->setDeal_credit($exsit_deal_credit + $default_post_credit);
                        $mbm_mapper->updateAll($mbmEntry[0]);
                        
                        $this->view->assign('action', $request->getBaseURL()."/product/sellerbid/pid/");
                        $this->view->assign('result', '新增成功!現在將轉到拍賣品頁面。');
                        $this->view->pbEntries = $pb_mapper->findByMemberId($sessLogin->mbmId);
			}
			$this->view->assign('title' , '訊息提示');
	        $this->view->assign('redirect' , '如果您的瀏覽器沒有自動跳轉，請點擊這裡');
		}
    }
    
    public function findbuyerAction()
    {
        
    }

    public function findsellerAction()
    {
        $request = $this->getRequest();
        $mbm_mapper = new Application_Model_MemberMapper();                       	

                       	$this->view->mbmEntries = $mbm_mapper->findByRandom();
                       	
                       	$this->view->assign('action', $request->getBaseURL()."/member/profile");
                       	$this->view->assign('productAction', $request->getBaseURL()."/product/sellerbid/lt/sb");
                       	$this->view->assign('discount' , '平均折扣: ');
                       	$this->view->assign('deal' , '最近交易: ');
                       	$this->view->assign('country' , '常駐地區 ');
    }

    public function sellerbidAction()
    {
        $request = $this->getRequest();
        $_pid = $request->getParam('pid');
        
        Zend_Date::setOptions(array('format_type' => 'php'));
        $date = new Zend_Date();
        
        $sessLogin = new Zend_Session_Namespace('Login');
        $pb_mapper = new Application_Model_ProductBuyMapper();
        $pb_bid_mapper = new Application_Model_ProductBuyBidMapper();
        $pb_offer_mapper = new Application_Model_ProductBuyOfferMapper();
        $product_browse_model = new Application_Model_ProductBrowse();
        $product_browse_mapper = new Application_Model_ProductBrowseMapper();
        
        $productBrowseEntries = $product_browse_mapper->findByPbidCreationTime($_pid, $date->toString('Y-m-d'));
		if(sizeof($productBrowseEntries) < 1){
			$product_browse_model->setProduct_buy_id($_pid);
			$product_browse_model->setAmount(1);
			$product_browse_model->setCreation_time($date->toString('Y-m-d'));
			$product_browse_mapper->insertAll($product_browse_model);
		}
        else{
	        $amount = $productBrowseEntries[0]->amount;
	        $amount++;
	        $productBrowseEntries[0]->amount = $amount;
	        $product_browse_mapper->updateAll($productBrowseEntries[0]);
        }
        
        $prodBuyEntry = $pb_mapper->findByProduct_buy_id($_pid);
        
        //$pb_mapper->updateAll($prodBuyEntry);
        
        $prodMbmBuyBidEntries = $pb_bid_mapper->findByPbIdMemberId($_pid, $sessLogin->mbmId);
        
        if(sizeof($prodMbmBuyBidEntries) > 0){
        	$this->view->hasBid = 'Y';
        	$this->view->prodMbmBuyBidEntries = $prodMbmBuyBidEntries;

        	$prodBuyOffEntries = $pb_offer_mapper->findByPbbIdOfferType($prodMbmBuyBidEntries[0]->product_buy_bid_id, 'O');
        	$prodBuyCOffEntries = $pb_offer_mapper->findByPbbIdOfferType($prodMbmBuyBidEntries[0]->product_buy_bid_id, 'CO');
        	
        	if(sizeof($prodBuyOffEntries) > 0){
        		$this->view->hasCounterOffer = 'N';
        		$this->view->hasOffer = 'Y';
        		$this->view->prodBuyOffEntries = $prodBuyOffEntries;
        	}
        	else if(sizeof($prodBuyCOffEntries) > 0){
        		$this->view->hasCounterOffer = 'Y';
        		$this->view->hasOffer = 'N';
        		$this->view->prodBuyCOffEntries = $prodBuyCOffEntries;
        	}
        	else{
        		$this->view->hasCounterOffer = 'N';
        		$this->view->hasOffer = 'N';
        	}
        	
        }
        else{
        	$this->view->hasBid = 'N';
        }
        
        if($prodBuyEntry[0]->member_id == $sessLogin->mbmId){
        	$this->view->isBuyer = 'Y';
        }
        else if($sessLogin->mbmId == null){
        	$this->view->isBuyer = 'L';
        }
        else{
        	$this->view->isBuyer = 'N';
        }
        
        $this->view->mbmId = $sessLogin->mbmId;
        $this->view->prodBuyEntry = $prodBuyEntry;
        $this->view->prodBuyBidEntries = $pb_bid_mapper->findByProduct_buy_id($prodBuyEntry[0]->product_buy_id);
        
        $this->view->assign('sellerBidAction' , '/bid/sellerbid');
        $this->view->assign('memberAction' , '/member/profile/mid/');
        $this->view->assign('counterOfferAction' , '/bid/counteroffer');
        $this->view->assign('cancelOfferAction' , '/bid/sellercanceloffer');
        $this->view->assign('creator' , '買家');
        $this->view->assign('price' , '價格');
        $this->view->assign('highest' , '最高價格');
        $this->view->assign('quantity' , '投標人數');
        $this->view->assign('winner' , '勝出者: ');
        $this->view->assign('history' , '投標歷史');
        $this->view->assign('bidder' , '投標者');
        $this->view->assign('time' , '時間');
        $this->view->assign('offer' , '出價');
        $this->view->assign('condition' , '條件');
        $this->view->assign('bid' , '投標');
        $this->view->assign('counterOffer' , '還價');
        $this->view->assign('accept' , '接受');
        $this->view->assign('reject' , '拒絕');
        $this->view->assign('cancel' , '取消此交易');
        $this->view->assign('done' , '成交');
        $this->view->assign('finished' , '已結束');
        $this->view->assign('loginPlease' , '請先登入');
        $this->view->assign('waitForReply' , '已出價, 等待買家回覆中');
        $this->view->assign('chooseOffer' , '請選擇投標歷史內的出價接受價格');
        $this->view->assign('accepted' , '已被接受');
        $this->view->assign('rejected' , '已被拒絕');
    }


}













